package bp.difference.context;

import java.util.regex.Pattern;

/**
 * xss安全解析Double值
 */
public class XSSSafeDoubleParser {

    private static final Pattern VALID_DOUBLE_PATTERN =
            Pattern.compile("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$");

    /**
     * 安全解析Double值，防止XSS攻击
     */
    public static double parse(String input) {
        return parse(input, null);
    }

    /**
     * 安全解析Double值，提供默认值
     */
    public static double parse(String input, Double defaultValue) {
        if (input == null) {
            return defaultValue;
        }

        // 移除所有空白字符
        String cleaned = input.replaceAll("\\s+", "");

        // 验证格式
        if (!VALID_DOUBLE_PATTERN.matcher(cleaned).matches()) {
            return defaultValue;
        }

        try {
            Double result = Double.valueOf(cleaned);

            // 防止特殊Double值
            if (result.isNaN() || result.isInfinite()) {
                return defaultValue;
            }

            return result;
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * 严格模式解析，包含范围检查
     */
    public static double parseStrict(String input, double min, double max) {
        Double value = parse(input);

        if (value == null) {
            throw new IllegalArgumentException("无效的数值格式");
        }

        if (value < min || value > max) {
            throw new IllegalArgumentException("数值超出允许范围: " + min + " - " + max);
        }

        return value;
    }
}